-------------------------------------------------------------------------------------------------------------


from langchain_openai import ChatOpenAI
from langchain_core.agents import Agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate

# 初始化语言模型
model = ChatOpenAI(model="gpt-3.5-turbo")

# 定义任务提示模板
search_prompt = ChatPromptTemplate.from_template("请帮助我找到与'{topic}'相关的信息。")
summarize_prompt = ChatPromptTemplate.from_template("请总结以下内容：{content}")

# 定义一个简单的搜索函数（在实际应用中，可以集成数据库或文档检索功能）
def search_for_info(topic):
    # 模拟搜索结果
    search_results = {
        "太空探索": "太空探索涉及人类发射探测器到外太空，以研究星系、行星等。",
        "海洋学": "海洋学是研究海洋及其生态系统的学科，涵盖海洋生物、化学和地质。",
    }
    return search_results.get(topic, "未找到相关信息")

# 定义一个Agent流程
class SimpleAgent(Agent):
    def plan(self, input):
        # 观察并提取主题
        topic = input["topic"]
        
        # 第一步：搜索相关信息
        search_result = search_for_info(topic)
        
        # 第二步：生成总结
        response = model.chat_completions.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": f"请总结以下内容：{search_result}"}]
        )
        
        # 返回最终生成的回答
        return {"summary": response.choices[0].message.content}

# 初始化AgentExecutor并执行任务
agent = SimpleAgent()
executor = AgentExecutor(agent=agent)

# 输入用户请求
user_input = {"topic": "太空探索"}
result = executor.invoke(user_input)
print("Agent的总结结果:", result["summary"])


-------------------------------------------------------------------------------------------------------------


from langchain_openai import ChatOpenAI
from langchain_core.agents import Agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate

# 初始化模型
model = ChatOpenAI(model="gpt-3.5-turbo")

# 模拟产品信息检索函数
def search_product_info(product_name):
    product_database = {
        "智能手机": "智能手机具有强大的多任务处理和高分辨率摄像头。",
        "无线耳机": "无线耳机具有降噪功能，适合运动和通勤。",
    }
    return product_database.get(product_name, "未找到该产品信息")

# 定义Agent
class ProductRecommendationAgent(Agent):
    def plan(self, input):
        # 获取用户输入的产品类别
        product_name = input["product"]
        
        # 第一步：检索产品信息
        product_info = search_product_info(product_name)
        
        # 第二步：生成推荐总结
        response = model.chat_completions.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": f"请总结该产品：{product_info}"}]
        )
        
        return {"recommendation": response.choices[0].message.content}

# 创建Agent执行器
agent = ProductRecommendationAgent()
executor = AgentExecutor(agent=agent)

# 测试用例
user_input = {"product": "智能手机"}
result = executor.invoke(user_input)
print("产品推荐总结:", result["recommendation"])


-------------------------------------------------------------------------------------------------------------


from langchain.agents import Tool, AgentExecutor, LLMSingleActionAgent, AgentOutputParser
from langchain.prompts import BaseChatPromptTemplate
from langchain import SerpAPIWrapper, LLMChain
from langchain.chat_models import ChatOpenAI
from typing import List, Union
from langchain.schema import AgentAction, AgentFinish, HumanMessage
import re
from getpass import getpass


SERPAPI_API_KEY = getpass("请输入您的SerpAPI密钥：")

# 设置搜索工具
search = SerpAPIWrapper(serpapi_api_key=SERPAPI_API_KEY)
tools = [
    Tool(
        name="Search",
        func=search.run,
        description="用于查询最新事件信息"
    )
]
template = """完成目标，您可以使用以下工具：

{tools}

请使用以下格式：

问题: 输入问题
思考: 思考应该采取的行动
操作: 选择的操作，使用 [{tool_names}] 中的工具
操作输入: 输入的操作
观察: 操作的结果
... (该步骤可以重复)
思考: 最终答案
最终答案: 原始问题的答案

历史任务完成情况：

开始！

问题: {input}
{agent_scratchpad}"""

# 定义自定义PromptTemplate
class CustomPromptTemplate(BaseChatPromptTemplate):
    template: str
    tools: List[Tool]

    def format_messages(self, **kwargs) -> str:
        intermediate_steps = kwargs.pop("intermediate_steps")
        thoughts = ""
        for action, observation in intermediate_steps:
            thoughts += action.log
            thoughts += f"\n观察: {observation}\n思考: "
        kwargs["agent_scratchpad"] = thoughts
        kwargs["tools"] = "\n".join([f"{tool.name}: {tool.description}" for tool in self.tools])
        kwargs["tool_names"] = ", ".join([tool.name for tool in self.tools])
        formatted = self.template.format(**kwargs)
        return [HumanMessage(content=formatted)]

prompt = CustomPromptTemplate(
    template=template,
    tools=tools,
    input_variables=["input", "intermediate_steps"]
)


class CustomOutputParser(AgentOutputParser):
    def parse(self, llm_output: str) -> Union[AgentAction, AgentFinish]:
        if "最终答案" in llm_output:
            return AgentFinish(llm_output.split("最终答案: ")[-1].strip())
        match = re.search(r"操作: (\w+)\n操作输入: (.*)", llm_output)
        if match:
            action = match.group(1)
            action_input = match.group(2)
            return AgentAction(action=action, action_input=action_input)
        raise ValueError(f"无法解析的输出: {llm_output}")


llm = ChatOpenAI(temperature=0)
agent = LLMSingleActionAgent(
    llm_chain=LLMChain(prompt=prompt, llm=llm),
    output_parser=CustomOutputParser(),
    stop=["\n"],
    tools=tools
)

executor = AgentExecutor(agent=agent, verbose=True)


# 提出示例问题
response = executor.invoke({"input": "现在的全球新闻是什么？"})
print("代理回答:", response)


-------------------------------------------------------------------------------------------------------------


from langchain.llms import OpenAI

# 初始化语言模型
llm = OpenAI(temperature=0)


from langchain.agents import load_tools

# 加载工具，使用llm支持的serpapi和llm-math
tools = load_tools(["serpapi", "llm-math"], llm=llm)


from langchain.agents import initialize_agent, AgentType

# 初始化ReAct Agent
agent = initialize_agent(
    tools=tools,
    llm=llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True
)
# 测试ReAct Agent
result = agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?")
print("ReAct Agent的回答:", result)


-------------------------------------------------------------------------------------------------------------


from langchain.llms import OpenAI
from langchain.agents import load_tools, initialize_agent, AgentType

# 初始化语言模型
llm = OpenAI(temperature=0)

# 加载工具
tools = load_tools(["serpapi", "llm-math"], llm=llm)

# 初始化ReAct Agent
react_agent = initialize_agent(
    tools=tools,
    llm=llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True
)

# 示例任务
result = react_agent.run("What is the distance from Earth to Mars in miles?")
print("ReAct Agent的回答:", result)


from langchain.agents import Tool, SQLDatabase, SQLDatabaseChain
from langchain.sql import SQLDatabase

# 配置数据库连接
db = SQLDatabase.from_uri("sqlite:///example.db")
db_chain = SQLDatabaseChain.from_llm(llm, db, verbose=True)

# 加载工具
tools = [
    Tool(name="Database Query", func=db_chain.run, description="Execute SQL queries.")
]

# 初始化Agent
functions_agent = initialize_agent(tools, llm, agent=AgentType.OPENAI_FUNCTIONS, verbose=True)

# 执行数据库查询任务
db_result = functions_agent.run("What are the latest entries in the sales database?")
print("数据库查询结果:", db_result)


from langchain.agents import initialize_agent, AgentType

# 使用Chat模型初始化对话Agent
chat_agent = initialize_agent(
    tools=tools, llm=llm, agent=AgentType.CHAT_CONVERSATION, verbose=True
)

# 示例对话
conversation_result = chat_agent.run("Can you summarize the latest news about space exploration?")
print("对话Agent的回答:", conversation_result)


from langchain.llms import OpenAI
from langchain.agents import load_tools, initialize_agent, AgentType, Tool
from langchain.sql import SQLDatabase
from langchain.agents import SQLDatabaseChain

# 初始化通用语言模型
llm = OpenAI(temperature=0)

# 加载搜索和计算工具
tools = load_tools(["serpapi", "llm-math"], llm=llm)

### 1. ReAct Agent 示例 ###
# 初始化ReAct Agent
react_agent = initialize_agent(
    tools=tools,
    llm=llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True
)

# 使用ReAct Agent执行信息检索和计算任务
react_result = react_agent.run("What is the distance from Earth to Mars in miles?")
print("ReAct Agent的回答:", react_result)


### 2. OpenAI Functions Agent 示例 ###
# 初始化数据库链
db = SQLDatabase.from_uri("sqlite:///example.db")
db_chain = SQLDatabaseChain.from_llm(llm, db, verbose=True)

# 定义数据库查询工具
db_tool = Tool(
    name="Database Query",
    func=db_chain.run,
    description="Execute SQL queries."
)

# 初始化OpenAI Functions Agent
functions_agent = initialize_agent(
    tools=[db_tool],
    llm=llm,
    agent=AgentType.OPENAI_FUNCTIONS,
    verbose=True
)

# 使用OpenAI Functions Agent执行数据库查询任务
db_result = functions_agent.run("What are the latest entries in the sales database?")
print("数据库查询结果:", db_result)


### 3. Chat Conversation Agent 示例 ###
# 初始化Chat Conversation Agent
chat_agent = initialize_agent(
    tools=tools, llm=llm, agent=AgentType.CHAT_CONVERSATION, verbose=True
)

# 使用Chat Conversation Agent保持对话上下文
conversation_result = chat_agent.run("Can you summarize the latest news about space exploration?")
print("对话Agent的回答:", conversation_result)


-------------------------------------------------------------------------------------------------------------


from langchain.llms import OpenAI
from langchain.agents import load_tools, initialize_agent, AgentType

# 初始化语言模型
llm = OpenAI(temperature=0)

# 加载工具，包括搜索和数学计算工具
tools = load_tools(["serpapi", "llm-math"], llm=llm)


# 初始化Zero-shot ReAct Agent
zero_shot_agent = initialize_agent(
    tools=tools,
    llm=llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True
)


# 测试任务：查询某城市当前天气
result = zero_shot_agent.run("What is the current weather in Tokyo?")
print("Zero-shot ReAct Agent的回答:", result)


# 测试任务：查询北京的空气质量指数
result = zero_shot_agent.run("请问北京的当前空气质量指数是多少？")
print("Zero-shot ReAct Agent的回答:", result)


-------------------------------------------------------------------------------------------------------------


from langchain.chat_models import ChatOpenAI
from langchain.agents.agent_toolkits import PlayWrightBrowserToolkit
from langchain.tools.playwright.utils import create_async_playwright_browser
import nest_asyncio

# 适用于Jupyter notebook，防止事件循环冲突
nest_asyncio.apply()

# 初始化浏览器工具
async_browser = create_async_playwright_browser()
browser_toolkit = PlayWrightBrowserToolkit.from_browser(async_browser=async_browser)
tools = browser_toolkit.get_tools()

# 初始化语言模型
llm = ChatOpenAI(temperature=0)


from langchain.agents import initialize_agent, AgentType

# 初始化结构化输入ReAct Agent
structured_agent = initialize_agent(
    tools=tools,
    llm=llm,
    agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True
)


import asyncio

# 使用结构化输入请求Agent执行任务
async def run_agent():
    response = await structured_agent.arun(input={
        "action": "navigate_browser",
        "action_input": {
            "url": "https://blog.langchain.dev/"
        }
    })
    print("结构化输入Agent的输出:", response)

# 执行异步任务
await run_agent()


-------------------------------------------------------------------------------------------------------------


from langchain.agents.react.base import DocstoreExplorer
from langchain import Wikipedia

# 创建文档存储库
docstore = DocstoreExplorer(Wikipedia())


from langchain.agents import Tool

# 配置工具
tools = [
    Tool(
        name="Search",
        func=docstore.search,
        description="适合用于需要进行搜索的查询"
    ),
    Tool(
        name="Lookup",
        func=docstore.lookup,
        description="适合用于需要精确查找的查询"
    ),
]


from langchain.llms import OpenAI
from langchain.agents import initialize_agent, AgentType

# 初始化语言模型
llm = OpenAI(temperature=0, model_name="text-davinci-002")

# 初始化ReAct Docstore Agent
react_agent = initialize_agent(
    tools=tools,
    llm=llm,
    agent=AgentType.REACT_DOCSTORE,
    verbose=True
)


# 示例问题
question = "作者David Chanoff曾与哪位美国海军上将合作，该上将在哪位总统任期内担任英国大使？"
response = react_agent.run(question)
print("ReAct Agent的回答:", response)


-------------------------------------------------------------------------------------------------------------


from langchain import Wikipedia
from langchain.agents.react.base import DocstoreExplorer

# 创建文档存储库，使用维基百科作为数据源
docstore = DocstoreExplorer(Wikipedia())


from langchain.agents import Tool

# 定义Search和Lookup工具
tools = [
    Tool(
        name="Search",
        func=docstore.search,
        description="适合用于一般性搜索查询"
    ),
    Tool(
        name="Lookup",
        func=docstore.lookup,
        description="适合用于特定信息查找"
    ),
]


from langchain.llms import OpenAI
from langchain.agents import initialize_agent, AgentType

# 初始化语言模型
llm = OpenAI(temperature=0, model_name="text-davinci-002")

# 初始化ReAct Docstore Agent
react_agent = initialize_agent(
    tools=tools,
    llm=llm,
    agent=AgentType.REACT_DOCSTORE,
    verbose=True
)


# 提出问题并获取答案
question = "莎士比亚的第一部作品是哪一部？"
response = react_agent.run(question)
print("ReAct Agent的回答:", response)
